package com.designpattern.softwaredesignpatternstudy.principle;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @Author: Jiangxx
 * @Date: 2021/11/02
 * @Description:
 */
public class Calculate {
    public static void main(String[] args) {
        //先定义一个逆波兰表达式
        String suffixExpression = "3 4 + 5 * 6 -";
        //思路：
        //1.先将"3 4 + 5 * 6 -"放到ArrayList中
        //2.将ArrayList传递给一个方法，遍历ArrayList配合栈完成计算
        List<String> list = getListStrings(suffixExpression);
        System.out.println("list="+list);
        int res = calculate(list);
        System.out.println("结果是"+res);
    }

    //将一个逆波兰表达式，依次将数据和运算符放入到ArrayList中
    public static List<String> getListStrings(String suffixExcepression){
        String [] split = suffixExcepression.split(" ");
        List<String> list =new ArrayList<String>();
        for(String ele:split) {
            list.add(ele);
        }
        return list;
    }

    public static int calculate(List<String> ls) {
        Stack<String> stack = new Stack<String>();
        for (String item : ls) {
            if (item.matches("\\d+")) {
                stack.push(item);
            } else {
                int num2 = Integer.parseInt(stack.pop());
                int num1 = Integer.parseInt(stack.pop());
                int res = 0;
                if (item.equals("+")) {
                    res = num1 + num2;
                } else if (item.equals("-")) {
                    res = num1 - num2;
                } else if (item.equals("*")) {
                    res = num1 * num2;
                } else if (item.equals("/")) {
                    res = num1 / num2;
                } else {
                    throw new RuntimeException("运算有误");
                }

                stack.push("" + res);

            }
        }
        return Integer.parseInt(stack.pop());
    }
}
